jsPlumb.ready(function () {
    var data = {
        "title": "工作流数据"
    };
    var lines = {},//线
        nodes = {},//节点
        index = 0;
    // 设置默认对象为jsPlumb
    var instance = jsPlumb.getInstance({
        Endpoint: ["Dot", {radius: 2}], //点的类型
        Connector: "Flowchart", //线的类型
        HoverPaintStyle: {stroke: "#7ab02c", strokeWidth: 2},//hover样式
        ConnectionOverlays: [  //箭头处的类型
            ["Arrow", {
                location: 1,//arrow 与初始点的位置
                id: "arrow", //arrow id
                length: 10, //arrow 尺寸大小
                foldback: 0.8 //箭头粗细度 值越小 arrow边缘越小
            }],
            //[ "Label", { label: "", id: "label", cssClass: "aLabel" }] //线上面的标记盒子
            ["Label", {
                location: 0.5,
                id: "label",
                cssClass: "aLabel",
                events: {
                    tap: function (e) {
                        //console.log("hi");
                    }
                }
            }]
        ],
        Container: "area" //必须为id
    });
    // anchor有四种类型：
    // static：固定不可移动的点
    // dynamic：从一组staticanchor中，每次动态选取一个合适的
    // perimeter：沿着特定图形的边
    // continous：没有固定的位置，根据线另一端点的朝向决定
    instance.registerConnectionType("basic", {anchor: "Continuous", connector: "Flowchart"}); //改变线的类型时这个一定要改
    window.jsp = instance;
    // 点击连线删除
    instance.bind("click", function (c, e) {
        if ($(e.target).attr("class") == "iconDiv") {
            if (confirm("确定删除吗?")) {
                instance.deleteConnection(c);
            }
        }
        /* else if ($(e.target).attr("class") == "editIcon") {
            showData(c, 0); // 0为线 1为div
            $(".hideBtn").trigger("click");
        }*/
    });
    instance.bind("connection", function (info) { //划线停止后mouseUp触发事件
        info.connection.getOverlay("label").setLabel(function () {
            /*var iconDiv = '<div class="iconDiv">\
                            <span class="editIcon"></span>\
                            <span class="deleteIcon"></span>\
                            <em class="lineN">' + info.connection.id + '</em>\
                        </div>';*/
            var iconDiv = '<div class="iconDiv" style="font-size: 20px;cursor: pointer;display: none">×</div>';
            return iconDiv;
        });
    });
    // 创建node 设置起始点，目标点.
    var initNode = function (el) {
        instance.draggable(el, {containment: "parent"}); //限制拖动不超过父级边框
        instance.makeSource(el, {
            filter: ".ep",
            anchor: "Continuous",
            connectorStyle: {stroke: "#ECE9F1", strokeWidth: 2},
            connectionType: "basic",
            extract: {"action": "the-action"},
            maxConnections: -1,
            onMaxConnections: function (info, e) { //最大连接数
                // alert("Maximum connections (" + info.maxConnections + ") reached");
            }
        });
        instance.makeTarget(el, { //连线箭头指向的终点位置，如果注销，连接失败
            dropOptions: {hoverClass: "dragHover"},
            anchor: "Continuous",
            allowLoopback: false,//自己连自己
        });
        // instance.fire("jsPlumbDemoNodeAdded", el);
    };
    //dom操作
    var getNodes = function () {
        $(".area .item").each(function () {
            nodes["node_" + $(this).attr("id")] = {
                // name: $(this).attr("data-name"),
                left: parseInt($(this).css("left")),
                top: parseInt($(this).css("top")),
                width: $(this).width(),
                height: $(this).height()
            };
        });
        return nodes;
    };
    //连接线信息
    var getLines = function (allLines) {
        var lineName;
        for (var i in allLines) {
            lineName = $("#" + allLines[i].getOverlay("label").canvas.id).find(".lineN").html();
            lines["line_" + allLines[i].id] = {
                "lineid": allLines[i].id,
                "name": lineName,
                "from": allLines[i].sourceId,
                "to": allLines[i].targetId
            };
        }
        return lines;
    };
    //右侧弹窗信息
    var showData = function (c) {
        // $(".conts .cont").eq(num).show().siblings(".cont").hide();
        /*if (num == 0) {
            $(".svgForm").find(".lineName").val(c.id).attr("oldId", c.id);
        } else {
            $(".conts .cont").eq(num).show().siblings(".cont").hide();
            $(".divForm input").eq(0).val(c.name).attr("oldId", c.id);
            $(".divForm input").eq(1).val(c.text);
        }*/
    };
    var operation = function () {
        //setStyle center
        /*$(".downDiv").css({height: $(".itemRight").height() - $(".area").height() - 14 + "px"});
        $(window).resize(function () {
            $(".downDiv").css({height: $(".itemRight").height() - $(".area").height() - 14 + "px"});
        });*/
        //rightDiv btn
        $(".hideBtn").on("click", function (c) {
            if (index == 0) {
                $(".rightDiv").animate({right: 0}, 500, function () {
                });
                index++;
            } else {
                $(".rightDiv").animate({right: -($(".rightDiv").outerWidth(true) + 10) + "px"}, 500, function () {
                });
                index--;
            }
        });
        //right arrow and rightDiv btn
        $(".arrowBtn,.save").on("click", function () {//右侧弹窗收缩
            $(".area").find('.item').removeClass('clickState');
            $(".rightDiv").animate({right: -($(".rightDiv").outerWidth(true) + 10) + "px"}, 500, function () {
                index = 0;
            });
        });
        $(".save").on("click", function () {
            /*if ($(".cont2").is(":visible")) { //div
                var newData = {};
                newData = {
                    oldId: $(".cont2").find("input").eq(0).attr("oldId"),
                    name: $(".cont2").find("input").eq(0).val(),
                    text: $(".cont2").find("input").eq(1).val()
                };
                $(".area .item").each(function () {
                    if (newData.oldId == $(this).attr("id")) {
                        $(this).attr("data-name", newData.name);
                        $(this).find(".text").text(newData.text);
                    }
                });
            } else {
                var newLineName = $(".lineName").val(),
                    oldLineId = $(".lineName").attr("oldId");
                var allLines = instance.getAllConnections();
                for (var index in allLines) {
                    if (allLines[index].id == oldLineId) {
                        $("#" + allLines[index].getOverlay("label").canvas.id).find(".lineN").html(newLineName)
                    }
                }
            }*/
        });
        $(document).on("mouseenter", ".area .item", function () {
            var ele = $('<span>×</span>');//button 删除按钮
            ele.css({
                position: "absolute",
                left: "80px",
                top: "-10px",
                width: 16 + "px",
                height: 16 + "px",
                textAlign: "center",
                lineHeight: 16 + "px",
                cursor: "pointer",
                fontSize: 20
            });
            $(this).append(ele);
        }).on("mouseleave", ".area .item", function () {
            $(this).find("span").remove();
        }).on("dblclick", ".area .item", function () {
            $(this).addClass("clickState");
            var nodeData = {
                id: $(this).attr("id"),
                name: $(this).attr("data-name"),
                text: $(this).find(".text").text()
            };
            $(".rightDiv").animate({right: 0 + "px"}, 500, function () {
                showData(nodeData, 1);
                index = 0;
            });
        }).on("click", ".area .item span", function () {
            if (confirm("确定删除吗?")) {
                var allLines = instance.getAllConnections($(this).parent().attr("id"));
                instance.removeAllEndpoints($(this).parent().attr("id")); //删除dom上所有点 官网detachAllConnections(el,[params]) 不好使
                $(this).parent().remove();
            }
        });
        //save date
        $(".saveData").on("click", function () {
            lines = {};
            nodes = {};
            var allLines = instance.getAllConnections();
            if (allLines.length != 0) {
                data.lines = getLines(allLines);
            } else {
                data.lines = lines = {};
            }
            data.nodes = getNodes();
            data.initNum = (Object.keys(data.lines).length + Object.keys(data.nodes).length);
            console.log(data);
        });
    };
    // 暂停绘图并初始化.
    instance.batch(function () {

        //数据
       /* var data = [
            {
                "id": "No1",
                "text": "搅拌"
            },
            {
                "id": "No2",
                "text": "投料"
            }
        ];
*/
        //先清空
        $(".item_top_con").html('');

        PostWebApi("queryAllOperate").done(function (data) {
            if (data.code == '0') {
                var info = data.data;
                info.forEach(function(d){
                    var item = '<div class="item"><i class="fa fa-fire" style="margin-right: 3px;"></i><p>' + d.operateName + '</p></div>';
                    $(".item_top_con").append(item);
                })
                $(".item_top_con .item").draggable({
                    helper: "clone",//clone可以让你A 拖到B 并复制
                    stop: function (e, ui) {
                        var left = parseInt(ui.offset.left - $(".area").offset().left);
                        var top = parseInt(ui.offset.top - $(".area").offset().top);
                        //拖动过来的元素   $(ui.helper).html()取 item 子级元素
                        var ele = $('<div class="item item_top">' + $(ui.helper).html() + '<div class="ep ep1"></div><div class="ep ep2"></div><div class="ep ep3"></div><div class="ep ep4"></div></div>')

                        if (ui.offset.left >= $(".area").offset().left) { //是否到拖放区域
                            ele.css({
                                "left": left,
                                "top": top,
                                position: "absolute",
                                margin: 0
                            });
                            $('.area').on("mouseenter", ".item", function () {
                                $(this).children('.ep').css('display', 'block')
                            }).on("mouseleave", ".item", function () {
                                $(this).children('.ep').css('display', 'none')
                            })
                            $(".area").append(ele);//拖动过来创建元素
                            initNode(ele);//调用方法
                        } else {
                            ele.remove();
                        }
                        //修复所有。当在中间区域拖动元素的时候，如果不带这一句，节点不会跟着元素一起移动。加上之后节点才会跟随标签移动。
                        jsPlumb.repaintEverything();
                    }
                });

            }
        })


        //遍历添加标签
/*        for (var i = 0; i < data.length; i++) {
            var item = '<div class="item"><i class="fa fa-fire" style="margin-right: 3px;"></i><p>' + data[i].text + '</p></div>';
            $(".item_top_con").append(item);
        }*/
        //元素标签可拖拽
/*        $(".item_top_con .item").draggable({
            helper: "clone",//clone可以让你A 拖到B 并复制
            stop: function (e, ui) {
                var left = parseInt(ui.offset.left - $(".area").offset().left);
                var top = parseInt(ui.offset.top - $(".area").offset().top);
                //拖动过来的元素   $(ui.helper).html()取 item 子级元素
                var ele = $('<div class="item item_top">' + $(ui.helper).html() + '<div class="ep ep1"></div><div class="ep ep2"></div><div class="ep ep3"></div><div class="ep ep4"></div></div>')

                if (ui.offset.left >= $(".area").offset().left) { //是否到拖放区域
                    ele.css({
                        "left": left,
                        "top": top,
                        position: "absolute",
                        margin: 0
                    });
                    $('.area').on("mouseenter", ".item", function () {
                        $(this).children('.ep').css('display', 'block')
                    }).on("mouseleave", ".item", function () {
                        $(this).children('.ep').css('display', 'none')
                    })
                    $(".area").append(ele);//拖动过来创建元素
                    initNode(ele);//调用方法
                } else {
                    ele.remove();
                }
                //修复所有。当在中间区域拖动元素的时候，如果不带这一句，节点不会跟着元素一起移动。加上之后节点才会跟随标签移动。
                jsPlumb.repaintEverything();
            }
        });*/

    });
    // jsPlumb.fire("jsPlumbDemoLoaded", instance);
    operation();
});